﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RuYiAdmin.Net.Common.Global;
using RuYiAdmin.Net.Entity.BusinessEntity.SystemManagement;
using RuYiAdmin.Net.Entity.BusinessEnum;
using RuYiAdmin.Net.Entity.CoreEntity;
using RuYiAdmin.Net.Service.BusinessService.SystemManagement.Log;
using RuYiAdmin.Net.WebApi.AppCode.Base;
using RuYiAdmin.Net.WebApi.AppCode.Filter;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace RuYiAdmin.Net.WebApi.Controllers.SystemManagement
{
    /// <summary>
    /// 日志管理控制器
    /// </summary>
    public class LogManagementController : BaseController<SysLog>
    {
        /// <summary>
        /// 日志接口实例
        /// </summary>
        private readonly ILogService logService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logService"></param>
        public LogManagementController(ILogService logService) : base(logService)
        {
            this.logService = logService;
        }

        /// <summary>
        /// 查询日志列表
        /// </summary>
        /// <param name="queryCondition">查询条件</param>
        /// <returns>ActionResult</returns>
        [HttpPost]
        [Log(OperationType.QueryList)]
        [Permission("log:query:list")]
        public IActionResult Post([FromBody] QueryCondition queryCondition)
        {
            var actionResult = this.logService.SqlQuery(queryCondition, "sqls:sql:query_syslog");
            return Ok(actionResult);
        }

        /// <summary>
        /// 获取日志明细
        /// </summary>
        /// <param name="logId">日志编号</param>
        /// <returns>ActionResult</returns>
        [HttpGet("{logId}")]
        [Log(OperationType.QueryEntity)]
        [Permission("log:query:entity")]
        public IActionResult GetById(Guid logId)
        {
            var actionResult = this.logService.GetById(logId);
            return Ok(actionResult);
        }

        /// <summary>
        /// 下载返回数据
        /// </summary>
        /// <param name="txtId">日志编号</param>
        /// <returns>ActionResult</returns>
        [HttpGet("{txtId}")]
        [Log(OperationType.DownloadFile)]
        public IActionResult DownloadMonitoringLog(String txtId)
        {
            //存储路径
            var path = Path.Join(GlobalContext.DirectoryConfig.GetMonitoringLogsPath(), "/");
            //文件名称
            var fileName = txtId + ".txt";
            //文件路径
            var filePath = Path.Join(path, fileName);
            //文件读写流
            var stream = new FileStream(filePath, FileMode.Open);
            stream.Position = 0;
            return File(stream, "application/octet-stream", fileName);
        }
    }
}
